<?php

namespace app\api\controller\pub;

use app\api\controller\Base;
use app\common\model\pub\Telbind;
use think\facade\Request;
use app\api\controller\Pub;

class TelTool extends Base
{
    /**
     * 流程
     * 数企系统 https://cdn.bdsaas.com/doc/cloudcall.pdf
     * 前置：创建数据库：表名[xxx_tel_bind],包含[phone]字段
     * 1、查询绑定[checkBind]：如果data为空证明已绑定，跳到第4步，
     * 2、获取验证码[imgCode]
     * 3、绑定手机号为坐席[bindPhone]
     * 4、请求回拨[dial]
     */


    private $app_key = '';
    private $code = '';


    public function initialize()
    {
        parent::initialize();
        $this->app_key = get_config_value('call_center_app_key');
        $this->code = get_config_value('call_center_code');
    }


    /**
     * 回拨
     *  "rspCode": 0,
     *  "rspMsg": null,
     *  "data": "badu1568853088920064000"   
     */
    public function dial($to_phone,$phone='')
    {
        $req = $this->request('bdsaas/call/phoneApi/callPhoneDispatch.do', [
            'appKey' => $this->app_key,
            // 'code' => $this->code,
            'seatPhone' => $phone,
            'toPhone' =>  $to_phone,
            'ip' => '112.229.160.10'//可不提交ip
        ]);
        if ($req['rspCode'] !== 0) {
            return serr($req['rspMsg']);
        }
        return sok($req);
    }

    /**
     * 删除坐席接口
     *  "坐席手机号",
     */
    public function deletePhone()
    {
        $userid = input('UserId');
        if(empty($userid)){
            return moerr('缺少关键参数');
        }
        //删除本地的
        $teldata = Telbind::get($userid);
        if(empty($teldata)){
            return myerr('没有找到回访中心记录');
        }
        $phone = $teldata['Iphone'];
        //远程删除服务端的
        $req = $this->request('bdsaas/call/phoneApi/closePhoneSeat.do', [
            'appKey' => $this->app_key,
            'seatPhone' => $phone,
        ]);
        if ($req['rspCode'] !== 0) {
            return moerr($req['rspMsg']);
        }
        //删除坐席信息
        $teldata = $teldata->delete();
        //回复成功
        return myok($req);
    }

    /**
     * 获取图形验证码
     */
    public function imgCode()
    {
        $req = $this->request('bdsaas/ajax/badu/callAgencyV2/phone/getImage.do');
        if ($req['statusCode'] != 0) {
            return myerr($req['msg']);
        }
        return myok([
            'code' => $req['data']['img'],
            'uuid' => $req['data']['uuid']
        ]);
    }

    /**
     * 发送手机验证码
     */
    public function smsCode()
    {
        $phone = Request::post('phone', '');
        $code = Request::post('code', '');
        $uuid = Request::post('uuid', '');
        //取消电话号码检测
        // if (!preg_match('/^1[3456789]\d{9}$/', $phone)) {
        //     return myerr('手机号格式错误');
        // }
        if (!$code || !$uuid) {
            return myerr('参数错误');
        }
        $req = $this->request('bdsaas/ajax/badu/callAgencyV2/phone/validImageCodeSendSmsCode.do', [
            'phone' => $phone,
            'imageCode' => $code,
            'uuid' => $uuid
        ]);
        if ($req['statusCode'] != 0) {
            return myerr($req['msg']);
        }
        return myok();
    }

    /**
     * 绑定手机号
     */
    public function bindPhone()
    {
        $phone = input('phone');
        $code = input('code');
        $userid = input('UserId');
        if(empty($userid)||empty($phone)||empty($code)){
            return moerr('缺少关键参数');
        }
        // if (!preg_match('/^1[3456789]\d{9}$/', $phone) || !$code) {
        //     return myerr('请检查填写信息');bdsaas/ajax/badu/callAgencyV2/phone/addPhoneSeatBySms.do
        // }
        $req = $this->request('bdsaas/call/phoneApi/addPhoneSeatBySms.do', [
            'appKey' => $this->app_key,
            // 'code' => $this->code,
            // 'otherUserId' => $phone,
            'seatPhone' => $phone,
            'smsCode' => $code
        ]);
        if ($req['rspCode'] != 0) {
            return moerr($req['rspMsg']);
        }
        Telbind::create([
            'UserId'=>$userid,
            'Iphone' => $phone
        ]);
        return myok();
    }


    private function msg($data)
    {
        return [
            'code' => true,
            'msg' => 'success',
            'data' => $data
        ];
    }

    public function request($path, $data = [])
    {
        $url = 'https://openapi.bdsaas.com/' . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        if ($data) {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data)); // 发送 JSON 数据
        }
        // dump($url);
        // dump($data);
          // 设置请求头
        $headers = [
            'Content-Type: application/json',
        ];
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); // 设置请求头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        curl_close($curl);
        if (!$response || $code != 200) {
            //错误强制返回
            return moerr('电话模块通讯失败，请联系管理员');
        }
        return json_decode($response, true);
    }
}